package org.jeecg.modules.demo.stockmanage.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.allvipcard.entity.AllVipcard;
import org.jeecg.modules.demo.allvipcard.service.IAllVipcardService;
import org.jeecg.modules.demo.basepayorder.entity.BasePayOrder;
import org.jeecg.modules.demo.basepayorder.service.IBasePayOrderService;
import org.jeecg.modules.demo.basestaffshareholder.entity.BaseStaffShareholder;
import org.jeecg.modules.demo.basestaffshareholder.service.IBaseStaffShareholderService;
import org.jeecg.modules.demo.membermanagement.entity.MemberManagement;
import org.jeecg.modules.demo.membermanagement.service.IMemberManagementService;
import org.jeecg.modules.demo.msgtemplatelist.entity.MsgTemplate;
import org.jeecg.modules.demo.msgtemplatelist.service.IMsgTemplateService;
import org.jeecg.modules.demo.staffmanagement.entity.StaffManagement;
import org.jeecg.modules.demo.staffmanagement.service.IStaffManagementService;
import org.jeecg.modules.demo.staffstockholder.service.IStaffStockholderService;
import org.jeecg.modules.demo.stockmanage.entity.*;
import org.jeecg.modules.demo.stockmanage.service.IStockManageService;
import org.jeecg.modules.demo.storeinfo.entity.StoreInfo;
import org.jeecg.modules.demo.storeinfo.service.IStoreInfoService;
import org.jeecg.modules.demo.vipcardcoupon.entity.VipCardCoupon;
import org.jeecg.modules.demo.vipcardcoupon.service.IVipCardCouponService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.util.HttpUtils;
import org.jeecg.modules.util.RedisUtils;
import org.jeecg.modules.util.ToolsUtils;
import org.jeecg.modules.weixin.util;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 股东管理
 */
@Api(tags = "股东管理")
@RestController
@RequestMapping("/stockmanage/stockManage")
@Slf4j
public class StockManageController extends JeecgController<StockManage, IStockManageService> {
    @Autowired
    IStaffStockholderService staffStockholderService;
    @Autowired
    private IStockManageService stockManageService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IStoreInfoService storeInfoService;
    @Autowired
    private IMemberManagementService memberManagementService;
    @Autowired
    private IStaffManagementService staffManagementService;
    @Autowired
    private IBaseStaffShareholderService baseStaffShareholderService;
    @Autowired
    private IAllVipcardService allVipcardService;
    @Autowired
    private IVipCardCouponService vipCardCouponService;
    @Autowired
    private IBasePayOrderService basePayOrderService;
    @Autowired
    private IMsgTemplateService msgTemplateListService;
    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "股东管理-分页列表查询")
    @ApiOperation(value = "股东管理-分页列表查询", notes = "股东管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(StockManage stockManage,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        QueryWrapper<StockManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("store_id", storeId);
    /*    if (!StringUtils.isEmpty(stockManage.getTel())){
            queryWrapper.like("tel", stockManage.getTel());
        }*/

        QueryGenerator.initQueryWrapper(queryWrapper, stockManage, req.getParameterMap());
        Page<StockManage> page = new Page<StockManage>(pageNo, pageSize);
        IPage<StockManage> pageList = stockManageService.page(page, queryWrapper);
        pageList.getRecords().forEach(sm -> {
            StaffManagement staff = staffManagementService.getById(sm.getShareholdersHousekeeperId());
            if (staff != null) {
                sm.setShareholdersHousekeeper(staff.getName());
            }
            int count = memberManagementService.count(new QueryWrapper<MemberManagement>().eq("store_id", storeId).eq("stock_id", sm.getId()));
            sm.setMemberQty(count);

            int icount = memberManagementService.count(new QueryWrapper<MemberManagement>().eq("store_id", storeId).eq("high_stock_id", sm.getId()));
            sm.setIndirectMemberQty(icount);
        });
        return Result.OK(pageList);
    }

    /**
     * 不分页列表查询
     */
    @AutoLog(value = "股东管理-不分页列表查询")
    @ApiOperation(value = "股东管理-不分页列表查询", notes = "股东管理-不分页列表查询")
    @GetMapping(value = "/listAll")
    public Result<?> queryPageList(StockManage stockManage,
                                   HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        QueryWrapper<StockManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, stockManage, req.getParameterMap());
        Page<StockManage> page = new Page<StockManage>(1, 100000);
        IPage<StockManage> pageList = stockManageService.page(page, queryWrapper);
        pageList.getRecords().forEach(sm -> {
            StaffManagement staff = staffManagementService.getById(sm.getShareholdersHousekeeperId());
            if (staff != null) {
                sm.setShareholdersHousekeeper(staff.getName());
            }
            int count = memberManagementService.count(new QueryWrapper<MemberManagement>().eq("store_id", storeId).eq("stock_id", sm.getId()));
            sm.setMemberQty(count);
        });
        return Result.OK(pageList);
    }

    @GetMapping(value = "/listStockBalanceRecord")
    public Result<?> listStockBalanceRecord(@RequestParam("stockId") String stockId,
                                            @RequestParam(name = "createTime", required = false) String createTime,
                                            @RequestParam(name = "name", required = false) String name,
                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                            HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        Page<Map<String, Object>> page = new Page<>(pageNo, pageSize);
        return Result.OK(stockManageService.listStockBalanceRecord(page, storeId, stockId, createTime, name));
    }

    @GetMapping(value = "/listStockDividendRecord")
    public Result<?> listStockDividendRecord(@RequestParam("stockId") String stockId,
                                             @RequestParam(name = "createTime", required = false) String createTime,
                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                             HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        IPage<Map<String, Object>> page = stockManageService.listStockDividendRecord(storeId, stockId, createTime, pageNo, pageSize);
        List<Map<String, Object>> records = page.getRecords();
        for (Map<String, Object> m : records) {
            if (m.get("dividendMoney") != null) {
                m.put("dividendMoney", ToolsUtils.formatNumber(m.get("dividendMoney")));
            }
        }
        return Result.OK(page);
    }

    @GetMapping(value = "/listStockWidthRecord")
    public Result<?> listStockWidthRecord(@RequestParam("stockId") String stockId,
                                          @RequestParam(name = "createTime", required = false) String createTime,
                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                          HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        return Result.OK(stockManageService.listStockWidthRecord(storeId, stockId, createTime, pageNo, pageSize));
    }

    /**
     * 分页列表查询
     */
    @AutoLog(value = "股东管理-获取没有绑定管家的股东")
    @ApiOperation(value = "股东管理-获取没有绑定管家的股东", notes = "股东管理-获取没有绑定管家的股东")
    @GetMapping(value = "/getList")
    public Result<?> getList(StockManage stockManage,
                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                             HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        QueryWrapper<StockManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, stockManage, req.getParameterMap());
        Page<StockManage> page = new Page<StockManage>(pageNo, pageSize);
        IPage<StockManage> pageList = stockManageService.searchStockList(page, stockManage.getStockName(), storeId);

        List<StockManage> lists = pageList.getRecords().stream().filter(o -> {
            QueryWrapper<BaseStaffShareholder> queryShareholder = new QueryWrapper<>();
            queryShareholder.eq("shareholder_id", o.getId());
            List<BaseStaffShareholder> b = baseStaffShareholderService.list(queryShareholder);
            boolean r = (b == null || b.isEmpty());
            return r;
        }).collect(Collectors.toList());
        pageList.setRecords(lists);

        return Result.OK(pageList);
    }

    /**
     * 查询股东统计数据
     */
    @AutoLog(value = "股东管理-查询股东统计数据")
    @ApiOperation(value = "股东管理-查询股东统计数据", notes = "股东管理-查询股东统计数据")
    @GetMapping(value = "/getStockDataCount")
    public Result<StockDataCount> getStockDataCount(@RequestParam(name = "storeId", defaultValue = "") String storeId,
                                                    @RequestParam(name = "stockId", defaultValue = "") String stockId) {
        Result<StockDataCount> result = new Result<>();
        StockDataCount stockDataCount = stockManageService.getStockDataCount(storeId, stockId);
        result.setSuccess(true);
        result.setResult(stockDataCount);
        return result;
    }

    /**
     * 查询股东股本统计
     */
    @AutoLog(value = "股东管理-查询股东股本统计")
    @ApiOperation(value = "股东管理-查询股东股本统计", notes = "股东管理-查询股东股本统计")
    @GetMapping(value = "/getStockEquityCount")
    public Result<StockEquityCount> getStockEquityCount(@RequestParam(name = "storeId", defaultValue = "") String storeId,
                                                        @RequestParam(name = "memberId", defaultValue = "") String memberId) {
        Result<StockEquityCount> result = new Result<>();
        StockEquityCount stockEquityCount = stockManageService.getStockEquityCount(storeId, memberId);
        result.setSuccess(true);
        result.setResult(stockEquityCount);
        return result;
    }

    /**
     * 查询股东分红统计
     */
    @AutoLog(value = "股东管理-查询股东分红统计")
    @ApiOperation(value = "股东管理-查询股东分红统计", notes = "股东管理-查询股东分红统计")
    @GetMapping(value = "/getStockDividendCount")
    public Result<StockDividendCount> getStockDividendCount(@RequestParam(name = "storeId", defaultValue = "") String storeId,
                                                            @RequestParam(name = "memberId", defaultValue = "") String memberId) {
        Result<StockDividendCount> result = new Result<>();
        StockDividendCount stockDividendCount = stockManageService.getStockDividendCount(storeId, memberId);
        result.setSuccess(true);
        result.setResult(stockDividendCount);
        return result;
    }

    /**
     * 查询没有股东管家的股东列表，用于添加员工时查股东列表
     */
    @RequestMapping(value = "/getNoHousekeeperStockList", method = RequestMethod.GET)
    public Result<?> getNoHousekeeperStockList(StockManage stockManage, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        Result<List<StockManage>> result = new Result<>();
        List<StockManage> list = stockManageService.getNoHousekeeperStockList(storeId);
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }

    @AutoLog(value = "股东管理-姓名电话列表")
    @ApiOperation(value = "股东管理-姓名电话列表", notes = "股东管理-姓名电话列表")
    @GetMapping(value = "/listForName")
    public Result<?> listForName(HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        QueryWrapper<StockManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("store_id", storeId);
        List<StockManage> listData = stockManageService.list(queryWrapper);
        List<Map<String, String>> newListData = new ArrayList<>();
        for (StockManage bean : listData) {
            Map<String, String> map = new HashMap<>();
            map.put("id", bean.getId());
            map.put("value", bean.getStockName() + "-" + bean.getTel());
            newListData.add(map);
        }
        return Result.OK(newListData);
    }

    /**
     * 添加股东时查股东拓客卡
     */
    @AutoLog(value = "股东管理-获取股东拓客卡")
    @ApiOperation(value = "股东管理-获取股东拓客卡", notes = "股东管理-获取股东拓客卡")
    @GetMapping(value = "/getTuoke")
    public Result<?> getTuoke(HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        QueryWrapper<AllVipcard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        queryWrapper.eq("card_type", "股东拓客卡");
        List<AllVipcard> list = allVipcardService.list(queryWrapper);

        list = list.stream().filter(av -> {
            List<VipCardCoupon> couponList = vipCardCouponService.list(new QueryWrapper<VipCardCoupon>()
                    .eq("store_id", storeId)
                    .eq("vip_id", av.getId()));
            Integer ticketNum = couponList.stream().map(VipCardCoupon::getNum).reduce(Integer::sum).orElse(0);
            return ticketNum > 0;
        }).collect(Collectors.toList());

        if (list.size() == 0) {
            return Result.error("还没有可用的股东拓客卡，请相关人员先创建股东拓客卡并绑定优惠劵");
        }

        return Result.OK(list);
    }

    /**
     * 一键关联人脉
     */
    @GetMapping(value = "/batchRelations")
    public Result<?> batchRelations(@RequestParam(value = "id", required = true) String id
            , HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        StockManage stockManage = stockManageService.getById(id);
        String memberId = stockManage.getMemberId();
        List<MemberManagement> list = memberManagementService.getRelations(memberId, storeId);
        for (int i = 0; i < list.size(); i++) {
            MemberManagement vMember = list.get(i);
            String vMemberId = vMember.getId();
            memberManagementService.updateStockId(id, vMemberId);
        }
        return Result.OK("OK");
    }

    /**
     * 添加
     */
    @AutoLog(value = "股东管理-添加")
    @ApiOperation(value = "股东管理-添加", notes = "股东管理-添加")
    @PostMapping(value = "/add")
    @Transactional(rollbackFor = JeecgBootException.class)
    public Result<?> add(@RequestBody StockManage stockManage, HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            storeId = stockManage.getStoreId();
        }
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        String memberId = stockManage.getMemberId();
        if (StringUtils.isEmpty(memberId)) {
            return Result.error("请传入会员ID");
        }
        String vipId = stockManage.getStockCard();
        if (StringUtils.isEmpty(vipId)) {
            return Result.error("请传入股东拓客卡ID");
        }
        if (stockManage.getIndirectProrateDividends() ==null){
            stockManage.setIndirectProrateDividends(Double.valueOf(0.0));
        }
        MemberManagement memberManagement = memberManagementService.getById(memberId);
        if (StringUtils.isNotEmpty(memberManagement.getMyStockId())) {
            return Result.error("该会员已是股东");
        }
        if (stockManage.getEquityTotal() <= 0) {
            return Result.error("入股金额需大于0");
        }
        if (stockManage.getStockLowest() < 0) {
            return Result.error("股本最低限额需大于0");
        }
        if (stockManage.getStockLowest() > stockManage.getEquityTotal()) {
            return Result.error("股本最低限额不能大于入股金额");
        }
        if (stockManage.getProrateDividends() < 0 || stockManage.getProrateDividends() > 100) {
            return Result.error("分红比例应在0-100之间");
        }
        if (stockManage.getIndirectProrateDividends() < 0 || stockManage.getIndirectProrateDividends() > 100) {
            return Result.error("分红比例应在0-100之间");
        }
        if (stockManage.getShareholderDiscount() < 0 || stockManage.getShareholderDiscount() > 10) {
            return Result.error("股东折扣应在0-10之间");
        }
        if (stockManage.getCardNum() <= 0) {
            return Result.error("发卡数量需大于0");
        }
        if (StringUtils.isNotEmpty(stockManage.getShareholdersHousekeeperId())) {
            if (stockManage.getShareholdersRatio() == null) {
                return Result.error("选择了股东管家，必须要填写股东提成比例");
            }
            if (stockManage.getMemberRatio() == null) {
                return Result.error("选择了股东管家，必须要填写股东会员提成比例");
            }
            if (stockManage.getShareholdersRatio() < 0 || stockManage.getShareholdersRatio() > 100) {
                return Result.error("股东提成比例在0-100之间");
            }
            if (stockManage.getMemberRatio() < 0 || stockManage.getMemberRatio() > 100) {
                return Result.error("股东会员提成比例应在0-100之间");
            }
        }

        stockManage.setEquityBalance(stockManage.getEquityTotal());
        stockManage.setInTime(new Date());
        stockManage.setTotalDividend(0.00);
        stockManage.setHaveWithdrawal(0.00);
        stockManage.setCanWithdrawal(0.00);
        stockManage.setDriveTurnover(0.00);
        stockManage.setTotalDividend(0.00);
        stockManage.setStoreId(storeId);
        stockManage.setShareholdersHousekeeper(null);
        stockManageService.save(stockManage);

        memberManagement.setMyStockId(stockManage.getId());
        memberManagement.setStatus("1");

        LambdaQueryWrapper<MemberManagement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MemberManagement::getMyStockId,memberManagement.getStockId());
        memberManagement.setHighStockId(memberManagementService.getOne(wrapper).getStockId());
        memberManagementService.updateById(memberManagement);

        // 下发股东拓客卡
        Result<?> result = allVipcardService.setIssuing4Stock(vipId, stockManage.getId(),
                stockManage.getCardNum(), storeId);
        if (result.getCode() == 500) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("发卡时发生错误：" + result.getMessage());
        }

        // 股本余额充值记录
        BasePayOrder basePayOrder = new BasePayOrder();
        basePayOrder.setOrderCode(ToolsUtils.getBillNo("MR"));
        basePayOrder.setRechargeAmount(stockManage.getEquityTotal());
        basePayOrder.setMemberName(memberManagement.getName());
        basePayOrder.setMemberPhone(memberManagement.getPhone());
        basePayOrder.setPayTime(new Date());
        basePayOrder.setStoreId(storeId);
        basePayOrder.setName("新建股东充值");
        basePayOrder.setMemberId(memberId);
        basePayOrder.setStockId(stockManage.getId());
        basePayOrderService.save(basePayOrder);

        // 模板消息
        try {
            MemberManagement mm = memberManagementService.getById(stockManage.getMemberId());
            String gzhOpenId = mm.getGzhOpenId();
            if (gzhOpenId == null) {
                log.info("发送成为股东模板推送失败，会员未绑定公众号");
            } else {
                StoreInfo store = storeInfoService.getById(storeId);
                if (store == null) {
                    log.info("发送成为股东模板推送失败，未查到店铺信息");
                } else {
                    String gzhAppId = store.getGzhAppId();
                    String gzhAppSecret = store.getGzhAppSecret();
                    if (StringUtils.isEmpty(gzhAppId) || StringUtils.isEmpty(gzhAppSecret)) {
                        log.info("发送成为股东模板推送失败，店铺未绑定公众号");
                    } else {
                        String url1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + gzhAppId + "&secret=" + gzhAppSecret;
                        String result1 = HttpUtils.sendGet(url1);
                        JSONObject resultJson1 = JSON.parseObject(result1);
                        String errcode = resultJson1.getString("errcode");
                        if (errcode != null && !"0".equals(errcode)) {
                            log.info("发送成为股东模板推送失败，获取accessToken返回值异常，错误码：{}", errcode);
                        } else {
                            String accessToken = resultJson1.getString("access_token");
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日 HH:mm");
                            MsgTemplate msgTemplate = msgTemplateListService.getByTitle("成为合伙人提醒", storeId);
                            String templateId = msgTemplate.getTemplateId();
                            util.becomeStockNotice(templateId, gzhOpenId, stockManage.getStockName(), sdf.format(new Date()), store.getXcxAppId(), "pages/user/index", accessToken);

                            log.info("发送成为股东模板推送成功");
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("发送成为股东模板推送失败，发生异常", e);
        }

        return Result.OK("添加成功！");
    }

    @AutoLog(value = "股东管理-编辑")
    @ApiOperation(value = "股东管理-编辑", notes = "股东管理-编辑")
    @PutMapping(value = "/edit")
    @Transactional(rollbackFor = JeecgBootException.class)//事物
    public Result<?> edit(@RequestBody StockManage stockManage, HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        StockManage old = stockManageService.getById(stockManage.getId());

        if (stockManage.getStockLowest() < 0) {
            return Result.error("股本最低限额需大于0");
        }
        if (stockManage.getStockLowest() > old.getEquityBalance()) {
            return Result.error("股本最低限额不能大于当前股本余额");
        }
        if (stockManage.getProrateDividends() < 0 || stockManage.getProrateDividends() > 100) {
            return Result.error("分红比例应在0-100之间");
        }
        if (stockManage.getIndirectProrateDividends() < 0 || stockManage.getIndirectProrateDividends() > 100) {
            return Result.error("分红比例应在0-100之间");
        }
        if (stockManage.getShareholderDiscount() < 0 || stockManage.getShareholderDiscount() > 10) {
            return Result.error("股东折扣应在0-10之间");
        }
        if (StringUtils.isNotEmpty(stockManage.getShareholdersHousekeeperId())) {
            if (stockManage.getShareholdersRatio() == null) {
                return Result.error("选择了股东管家，必须要填写股东提成比例");
            }
            if (stockManage.getMemberRatio() == null) {
                return Result.error("选择了股东管家，必须要填写股东会员提成比例");
            }
            if (stockManage.getShareholdersRatio() < 0 || stockManage.getShareholdersRatio() > 100) {
                return Result.error("股东提成比例在0-100之间");
            }
            if (stockManage.getMemberRatio() < 0 || stockManage.getMemberRatio() > 100) {
                return Result.error("股东会员提成比例应在0-100之间");
            }
        }

        stockManage.setTel(null);
        stockManage.setMemberId(null);
        stockManage.setShareholdersHousekeeper(null);
        stockManageService.updateById(stockManage);

        if (StringUtils.isEmpty(stockManage.getShareholdersHousekeeperId())) {
            stockManageService.cleanShareholdersHousekeeper(stockManage.getId());
        }

        return Result.OK("编辑成功！");
    }

    @AutoLog(value = "股东管理账号-添加")
    @ApiOperation(value = "股东管理账号-添加", notes = "股东管理账号-添加")
    @PostMapping(value = "/addAccount")
    public Result<?> addAccount(@RequestBody StockManage stockManage, HttpServletRequest req) {
        //HttpServletRequest req
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        //店铺管理员 才有权限添加 店员

        //联系方式 为账号
        String username = stockManage.getTel();
        String password = "123456";
        if (oConvertUtils.isEmpty(username)) {
            return Result.error("请输入联系方式");
        }

        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username);
        SysUser userv = sysUserService.getOne(queryWrapper);
        if (userv == null) {
            SysUser user = new SysUser();
            user.setCreateTime(new Date());//设置创建时间
            user.setUsername(username);
            user.setPassword(password);
            user.setRealname(stockManage.getStockName());
            user.setStoreId(storeId);
            String salt = oConvertUtils.randomGen(8);
            user.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
            user.setPassword(passwordEncode);
            user.setStatus(1);
            user.setDelFlag(CommonConstant.DEL_FLAG_0);
            //生成股东角色账号号
            sysUserService.saveUser(user, "1484029201071419393", "");

            StoreInfo storeInfo = storeInfoService.getById(storeId);
            stockManage.setSysOrgCode(storeInfo.getStoreName());
            stockManage.setStoreId(storeId);
            stockManageService.save(stockManage);

            return Result.OK("添加成功！");
        } else {
            return Result.error("已存在的联系方式");
        }
    }


    /**
     * 编辑
     *
     * @param stockManage
     * @return
     */
    @AutoLog(value = "股东管理账号-编辑")
    @ApiOperation(value = "股东管理账号-编辑", notes = "股东管理账号-编辑")
    @PutMapping(value = "/editAccount")
    public Result<?> editAccount(@RequestBody StockManage stockManage, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        String username = stockManage.getTel();
        String password = "123456";
        if (oConvertUtils.isEmpty(username)) {
            return Result.error("请输入联系方式");
        }

        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username);
        SysUser userv = sysUserService.getOne(queryWrapper);
        if (userv == null) {
            SysUser user = new SysUser();
            user.setCreateTime(new Date());//设置创建时间
            user.setUsername(username);
            user.setPassword(password);
            user.setRealname(stockManage.getStockName());
            user.setStoreId(storeId);
            String salt = oConvertUtils.randomGen(8);
            user.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
            user.setPassword(passwordEncode);
            user.setStatus(1);
            user.setDelFlag(CommonConstant.DEL_FLAG_0);
            //生成股东角色账号号
            sysUserService.saveUser(user, "1484029201071419393", "");
            stockManage.setStoreId(storeId);
        }

        stockManageService.updateById(stockManage);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "股东管理-通过id删除")
    @ApiOperation(value = "股东管理-通过id删除", notes = "股东管理-通过id删除")
    @DeleteMapping(value = "/delete")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        memberManagementService.update(new MemberManagement().setMyStockId(""), new QueryWrapper<MemberManagement>().eq("my_stock_id", id));
        memberManagementService.update(new MemberManagement().setStockId("").setStatus("2").setMemberType("店铺会员").setStockMemberExpendamount(0.00), new QueryWrapper<MemberManagement>().eq("stock_id", id));
        stockManageService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "股东管理-批量删除")
    @ApiOperation(value = "股东管理-批量删除", notes = "股东管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
//        for (int i = 0; i < Arrays.asList(ids.split(",")).size(); i++) {
//            memberManagementService.updateMemberType("店铺会员",Arrays.asList(ids.split(",")).get(i));
//        }
//        this.stockManageService.removeByIds(Arrays.asList(ids.split(",")));
//
//        return Result.OK("批量删除成功!");
        return Result.error("暂时不支持批量删除");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "股东管理-通过id查询")
    @ApiOperation(value = "股东管理-通过id查询", notes = "股东管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        StockManage stockManage = stockManageService.getById(id);
        if (stockManage == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(stockManage);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param stockManage
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StockManage stockManage) {
        //return super.exportXls(request, stockManage, StockManage.class, "股东管理");
        String token = TokenUtils.getTokenByRequest(request);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);

        // Step.1 组装查询条件
        QueryWrapper<StockManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, stockManage, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<StockManage> pageList = stockManageService.list(queryWrapper);
        pageList.forEach(sm -> {
            StaffManagement staff = staffManagementService.getById(sm.getShareholdersHousekeeperId());
            if (staff != null) {
                sm.setShareholdersHousekeeper(staff.getName());
            }
            int count = memberManagementService.count(new QueryWrapper<MemberManagement>().eq("store_id", storeId).eq("stock_id", sm.getId()));
            sm.setMemberQty(count);
        });

        // Step.3 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "股东列表"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, StockManage.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams("股东列表数据", "导出人:" + user.getRealname(), "股东列表");
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, StockManage.class);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param stockId
     */
    @RequestMapping(value = "/exportXlsDividend")
    public ModelAndView exportXlsDividend(HttpServletRequest request, String stockId) {
        //return super.exportXls(request, stockManage, StockManage.class, "股东管理");
        String token = TokenUtils.getTokenByRequest(request);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<StockDividend> listStockDividend = stockManageService.getListStockDividend(stockId);
        // Step.3 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "总分红金额"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, StockDividend.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams("总分红金额", "导出人:" + user.getRealname(), "总分红金额");
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, listStockDividend);
        return mv;
    }
}
